package com.richapp.launcher.serialport.gateway;


import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelDao;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.database.system.mode.DeviceModel;
import com.richapp.launcher.gpio.GPIOServer;
import com.richapp.launcher.net.box.tcp.server.BoxServer;
import com.richapp.launcher.net.message.MsgConstant;
import com.richapp.launcher.net.mobile.message.DeviceDoFailReply;
import com.richapp.launcher.net.mobile.server.UserServer;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.net.util.HexTool;

public class GatewayWriteThread implements Runnable {
	private static final String TAG = GatewayWriteThread.class.getName();
	private boolean runFlag = false;
	private ConcurrentLinkedQueue<ControlInstructionMessage> messageList = new ConcurrentLinkedQueue<ControlInstructionMessage>();
	private OutputStream os = null;
	private DeviceModelDao deviceModelDao = new DeviceModelDao(GatewayServer.getInstance().getContext());
	@Override
	public void run() {
		ControlInstructionMessage controlInstructionMessage=null;
		Log.d(TAG, "网关信息写入线程启动");
		while(runFlag){
			try {
				//校对指令令牌时候生效，如果生效，发送校对指令
				if(GatewayServer.isClearFlag()){
//					Log.d(TAG, "发送校对指令:" + GatewaytConstant.INSTRUCTION_PROOFREADING_STR);
//					os.write(HexTool.HexToByteArr(GatewaytConstant.INSTRUCTION_PROOFREADING_STR));
//					os.flush();
//					//发送后，校对指令失效
					GatewayServer.setClearFlag(false);
				}else{
					//判断最后一条指令，如果为空或者收到执行结果，开始执行下一条指令
					if(GatewayServer.getLastMessage() == null || GatewaytConstant.INSTRUCTION_DO_RESULT_DATA.equals(GatewayServer.getLastMessage().getInstructionDoResult())){

						controlInstructionMessage = messageList.poll();
						if(controlInstructionMessage != null){
							if(!GatewaytConstant.INSTRUCTION_PROOFREADING_STR.equals(controlInstructionMessage.getHexInstruction())
									&& !GatewaytConstant.INSTRUCTION_RESET_ALL_STR.equals(controlInstructionMessage.getHexInstruction())){
								//保存最后一条指令
								GatewayServer.setLastMessage(controlInstructionMessage);
							}
							//设置指令开始时间
							controlInstructionMessage.setStartTime(System.currentTimeMillis());
								Log.d(TAG,"向网关串口写入:" + controlInstructionMessage.getHexInstruction());
								os.write(HexTool.HexToByteArr(controlInstructionMessage.getHexInstruction()));
								os.flush();
							//闪光
							GPIOServer.getInstance().lightFlash();

						}
					}else{
						//判断超时时间，等待执行结果
						if((GatewayServer.getLastMessage().getInstructionResult() == null)
								&& !GatewaytConstant.INSTRUCTION_DO_RESULT_BUSY.equals(GatewayServer.getLastMessage().getInstructionDoResult())
								&& !GatewaytConstant.INSTRUCTION_DO_RESULT_FAIL.equals(GatewayServer.getLastMessage().getInstructionDoResult())){
							//判断指令执行时间
							long passTime = System.currentTimeMillis() - GatewayServer.getLastMessage().getStartTime();
							if(passTime > GatewayServer.getLastMessage().getTimeOut()){
								//指令执行超时
								Log.d(getClass().getName(),"执行指令超时");
								GatewayServer.setLastMessage(null);
							}else{
								Log.d(getClass().getName(),"等待执行结果，为了线程CPU消耗，休息等待结果");
								//等待执行结果，为了线程CPU消耗，休息等待结果
								Thread.sleep(GatewaytConstant.INSTRUCTION_SEND_SLEEP_TIME/5);
							}
						}else{	//否则，发送ERRO或者执行结果BUSY,FAIL,都认为指令发送失败
							if(GatewayServer.getLastMessage().getFailCount() > 0 ){
								Log.d(getClass().getName(),"ERRO或者执行结果BUSY,FAIL,都认为指令发送失败");

								//发送fail到前端和服务器
								DeviceDoFailReply ddfr = new DeviceDoFailReply();
								BoxModel ctBox = new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox();
								ddfr.setCurrentBoxCpuId(ctBox.getBoxCpuId());
								ddfr.setUserName(ctBox.getUserName());

								DeviceModel dm = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(GatewayServer.getLastMessage().getBoxCpuId(), GatewayServer.getLastMessage().getDeviceId(), GatewayServer.getLastMessage().getDeviceNumer(),GatewayServer.getLastMessage().getWay());
								if(dm != null){
									ddfr.setDeviceModel(dm);
									JSONObject jsonObject = (JSONObject)JSON.toJSON(ddfr);

									//发送所有当前手机
									UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

									if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
										jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
										//发送服务器
										RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
										//发送其他机顶盒
										BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
									}
								}
								GatewayServer.setLastMessage(null);
							}else{
								Log.d(TAG,"指令失败计数出错啦!");
							}
						}
					}
				}
			} catch (Exception e) {
				Log.e(TAG, "发送线程出错:" + e.getMessage());
			}
		}
		Log.e(TAG, "网关信息写入线程关闭");
	}
	
	public void writeOneMessage(ControlInstructionMessage msg){
		messageList.add(msg);
	}

	public boolean isRunFlag() {
		return runFlag;
	}

	public void setRunFlag(boolean runFlag) {
		this.runFlag = runFlag;
	}

	public OutputStream getOs() {
		return os;
	}

	public void setOs(OutputStream os) {
		this.os = os;
	}


}
